// pages/news/index/index.js
import {getCate, getList} from "../../../service/News";
import {getResult} from "../../../service/Questionnaire";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        active: "",
        cateList: [], //分类
        news: {
            list: [],
            loading: false,
            reset: false,
            error: false,
            total: 0
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getNewsCate();
    },

    /*
    * 获取动态分类
    * */
    getNewsCate: async function () {
        try {
            const that = this;
            let res = await getCate();
            this._cid = res[0].cid;
            this.setData({
                cateList: res,
                "news.loading": true
            }, function () {
                setTimeout(function () {
                    that.setData({active: 0})
                }, 200)
            });
        } catch (e) {
            console.error(e)
        }
    },

    /*
    * 监听列表加载
    * */
    onLoadList: async function (e) {
        try {
            let paging = e.detail.paging;
            let list = this.data.news.list;
            let isReset = this.data.news.reset;
            let res = await getList({
                "cid": this._cid,
                "page": paging.page,
                "per-page": paging.pageSize
            });
            let newList = res.itemList;
            list = isReset ? newList : list.concat(newList);
            this.setData({
                "news.list": list,
                "news.reset": false,
                "news.loading": false,
                "news.total": res.totalCount
            });
        } catch (e) {
            this.setData({
                "news.error": true
            })
        }
    },

    /*
    * tabs切换
    * */
    onTabsChange: function (e) {
        const that = this;
        clearTimeout(that._onTabsChange);
        that._onTabsChange = setTimeout(function () {
            let {index} = e.detail;
            let cateList = that.data.cateList;
            that._cid = cateList[index].cid;
            that.setData({
                "news.list": [],
                "news.reset": true
            })
        }, 300)
    },

    /*
    * 点击查看详情
    * */
    bindItem: function (e) {
        let index = e.currentTarget.dataset.index;
        let list = this.data.news.list;
        let currentItem = list[index];
        wx.navigateTo({
            url: "/pages/news/detail/detail?id=" + currentItem.id
        })
    },


    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.setData({"news.loading": true})
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})